package com.ztjava.score.service;

import java.util.List;

import com.ztjava.core.base.BaseService;
import com.ztjava.score.model.level.LevelInfo;
import com.ztjava.score.model.level.LevelSeries;
import com.ztjava.score.model.level.LevelType;

public class LevelService extends BaseService{
	/**
	 * 更新用户等级
	 * @param score_type_id
	 * @param user_id
	 * @param score
	 */
	public void updateUserLevel(Integer score_type_id,Integer user_id,Integer score){
		List<LevelSeries> seriesList = LevelSeries.dao.find("select * from "+LevelSeries.tablename+" where score_type_id=?",score_type_id);
		for(int i=0;i<seriesList.size();i++){
			LevelType levelType = LevelType.dao.findFirst("select * from "+LevelType.tablename+" where series_id=? and min_score<=? and max_score>=?",seriesList.get(i).getInt("id"),score,score);
			if(levelType!=null){
				LevelInfo levelInfo = LevelInfo.dao.findFirst("select * from "
						+LevelInfo.tablename+" where user_id=? and type_id=? and series_id=?"
						,user_id,levelType.getInt("id"),seriesList.get(i).getInt("id"));
				if(levelInfo==null){
					levelInfo = new LevelInfo();
					levelInfo.set("user_id", user_id);
					levelInfo.set("type_id", levelType.getInt("id"));
					levelInfo.set("series_id", seriesList.get(i).getInt("id"));
					levelInfo.set("create_user", user_id);
					levelInfo.save();
				}else {
					if(!levelInfo.getInt("type_id").equals(levelType.getInt("id"))){
						levelInfo.set("type_id", levelType.getInt("id")).update();
					}
				}
			}
		}
	}
}
